﻿using System.Diagnostics;
using System.IO.Ports;
using System.Windows.Threading;

namespace SerialDemo.Services
{
    public class SerialPortService:ISerialPortService
    {

        private SerialPort serialPort;
        private readonly Dispatcher _dispatcher;

        public event EventHandler<string> DataReceived;

        public SerialPortService(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }

        public string[] GetPort()
        {
            return SerialPort.GetPortNames();
        }

        public void Open(string port, int baudRate)
        {
            serialPort = new SerialPort(port, baudRate, Parity.None, 8, StopBits.One);
            serialPort.DataReceived += SerialPort_DataReceived;
            serialPort.Open();

        }

        public bool GetStatus()
        {
            if(serialPort!=null)
                return serialPort.IsOpen;
            return false;
        }

        public void Close()
        {
            serialPort?.Close();
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            try
            {
                var sp = (SerialPort)sender;
                var data = sp.ReadLine();
                //Invoke：这是一个同步方法，它会阻塞当前线程，直到主线程完成指定的操作。如果你希望异步执行操作，可以使用 _dispatcher.BeginInvoke
                _dispatcher.BeginInvoke(() =>
                {
                    //这是一个匿名委托，表示要在线程上执行的操作
                    //DataReceived：这是一个事件，表示当串口接收到数据时触发。
                    //this：表示事件的发送者，通常是当前对象。
                    DataReceived?.Invoke(this, data);
                });
            }
            catch (Exception ex)
            {

                Debug.WriteLine($"Error in SerialPort_DataReceived:{ex.Message}");
            }
        }


        public void Write(string data)
        {
            if (serialPort != null && serialPort.IsOpen)
                serialPort.WriteLine(data);
        }


    }
            
}
